package com.example.sociamedia.interaction.controller;

import com.example.sociamedia.interaction.dto.NotificationRequest;
import com.example.sociamedia.interaction.dto.NotificationResponse;
import com.example.sociamedia.interaction.entity.Notification;
import com.example.sociamedia.interaction.mapper.NotificationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class NotificationService implements NotificationApi {
    private final NotificationMapper notificationMapper;

    @Autowired
    public NotificationService(NotificationMapper notificationMapper) {
        this.notificationMapper = notificationMapper;
    }

    @Override
    public NotificationResponse addNotification(NotificationRequest request) {
        Notification notification = new Notification();
        notification.setUserId(request.getUserId());
        notification.setSenderId(request.getSenderId());
        notification.setType(request.getType());
        notification.setRelatedId(request.getRelatedId());
        notificationMapper.insertNotification(notification);
        NotificationResponse resp = new NotificationResponse();
        resp.setSuccess(true);
        resp.setMessage("通知添加成功");
        resp.setNotificationId(notification.getNotificationId());
        resp.setUserId(notification.getUserId());
        resp.setSenderId(notification.getSenderId());
        resp.setType(notification.getType());
        resp.setRelatedId(notification.getRelatedId());
        resp.setCreatedAt(notification.getCreatedAt());
        resp.setIsRead(notification.getIsRead());
        return resp;
    }

    @Override
    public List<Notification> getNotifications(Long userId, boolean onlyUnread) {
        if (onlyUnread) {
            return notificationMapper.selectUnreadByUserId(userId);
        } else {
            return notificationMapper.selectAllByUserId(userId);
        }
    }

    @Override
    public NotificationResponse markAsRead(Long userId, Long notificationId) {
        NotificationResponse resp = new NotificationResponse();
        int count = notificationMapper.markAsRead(notificationId, userId);
        if (count > 0) {
            resp.setSuccess(true);
            resp.setMessage("标记为已读成功");
        } else {
            resp.setSuccess(false);
            resp.setMessage("通知不存在或已读");
        }
        return resp;
    }

    @Override
    public NotificationResponse markAllAsRead(Long userId) {
        NotificationResponse resp = new NotificationResponse();
        int count = notificationMapper.markAllAsRead(userId);
        resp.setSuccess(true);
        resp.setMessage("全部标记为已读，共" + count + "条");
        return resp;
    }

    @Override
    public int countUnread(Long userId) {
        return notificationMapper.countUnread(userId);
    }
} 